package jasperreport;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRGraphics2DExporter;
import net.sf.jasperreports.engine.export.JRGraphics2DExporterParameter;

public class ImageTest implements Servlet{

	@Override
	public void destroy() {
		
	}

	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
	public String getServletInfo() {
		return null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		
	}

	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		
		res.setContentType("application/jpeg");
		((HttpServletResponse)res).addHeader("content-disposition", "attachment;filename=chart.jpg");
		ServletOutputStream out = res.getOutputStream();
		InputStream in = this.getClass().getResourceAsStream("report3.jasper");
		List<Chart> stus = Chart.get();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", "fugui");
		JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(stus);
		
		try {
			JasperPrint print = JasperFillManager.fillReport(in, map, dataSource);
			JRGraphics2DExporter exporter = new JRGraphics2DExporter();
			BufferedImage image = new BufferedImage(print.getPageWidth() * 4, print.getPageHeight() * 4, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = (Graphics2D)image.getGraphics();
			exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, g);
			exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(4));
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			exporter.exportReport();
			g.dispose();
			ImageIO.write(image, "JPEG", out);
		} catch (JRException e) {
			e.printStackTrace();
		}
	}
}
